﻿"use strict";
var connection = new signalR.HubConnectionBuilder()
    .withUrl("/noti")
    .withAutomaticReconnect([2000, 4000, 6000, 8000, 10000, 12000, 14000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000, 16000])
    .build();
connection.onclose(function (error) {
    document.getElementById("connectionState").textContent = "Disconnected. Please refrech web page.";

});
connection.onreconnecting(function (error) {
  
    document.getElementById("connectionState").textContent = "Reconnecting...";
});
connection.onreconnected(function (connectionId) {
    document.getElementById("connectionState").textContent = "Connected";

});
connection.on("Plate", function (plate, image64, transactionType, date) {
    if (transactionType == "1") {//1:in 2:out
        document.getElementById("in_titledate").textContent = "IN (" + date + ")";
        document.getElementById("in_plate").textContent = plate;
        document.getElementById("in_img").src = "data:image/png;base64," + image64;
    } else if (transactionType == "2") {
        document.getElementById("out_titledate").textContent = "OUT (" + date + ")";
        document.getElementById("out_plate").textContent = plate;
        document.getElementById("out_img").src = "data:image/png;base64," + image64;
    }
    //console.log(plate, image64, transactionType);
});

connection.start().then(function () {
    document.getElementById("connectionState").textContent = "Connected";
}).catch(function (err) {
    return alert("請重新整理頁面")
});

connection.on("newRecord", updateRecord)

function updateRecord(newRecord) {
    console.log(newRecord);
    const time = newRecord.date.substring(11)
    if (newRecord.transactionTypeID == "1") {//1:in 2:out
        document.getElementById("in_titledate").textContent = "IN (" + time + ")";
        document.getElementById("in_plate").textContent = newRecord.plate;
        document.getElementById("in_img").src = `${imgUrl}${newRecord.id}`;
    } else if (newRecord.transactionTypeID == "2") {
        document.getElementById("out_titledate").textContent = "OUT (" + time + ")";
        document.getElementById("out_plate").textContent = newRecord.plate;
        document.getElementById("out_img").src = `${imgUrl}${newRecord.id}`;
    }

    const tbody = document.querySelector("table.records tbody")
    let tr = document.createElement('tr')
    tr.classList.add("slideIn")
    tr.innerHTML = `
        <td>${newRecord.date}</td>
        <td>${newRecord.plate}</td>
        <td>${newRecord.isValidPlate}</td>
        <td>${newRecord.ip} <span class="text-black-50">/${newRecord.parkingPlaceId}</span></td>
        <td><img src="${imgUrl}${newRecord.id}" class="img-carplate" /></td>
    `
    tbody.prepend(tr)
}